package com.example.shop_management.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.shop_management.entity.Goods;
import com.example.shop_management.entity.Orders;
import com.example.shop_management.entity.User;
import com.example.shop_management.service.impl.GoodsServiceImpl;
import com.example.shop_management.service.impl.OrdersServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("orders")
public class OrdersController {

    @Autowired
    private OrdersServiceImpl ordersService;

    @Autowired
    private GoodsServiceImpl goodsService;

    @GetMapping("findall")
    public List<Orders> findall() {
        QueryWrapper<Orders> OrdersQueryWrapper = new QueryWrapper<>();
        OrdersQueryWrapper.orderByDesc("create_time");
        List<Orders> list = ordersService.list(OrdersQueryWrapper);
        for(Orders orders:list){
            orders.setGoods(goodsService.getById(orders.getGid()));
        }
        return list;
    }


    @PostMapping("save")
    public boolean insert(@RequestBody Orders orders){
        boolean flag = ordersService.saveOrUpdate(orders);
        Integer goodsCount = orders.getGoodsCount();
        Goods goods = goodsService.getById(orders.getGid());
        goods.setInventory(goods.getInventory()- goodsCount);
        goodsService.saveOrUpdate(goods);
        return flag;
    }

    @PostMapping("delete")
    public boolean delete(@RequestBody int id){
        return ordersService.removeById(id);
    }

    @PostMapping("deleltebatch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return ordersService.removeByIds(ids);
    }

    //条件查询
    @GetMapping("selectbycondition")
    public List<Orders> selectByCondition(@RequestParam(defaultValue = "",required = false) String uid,
                                        @RequestParam(defaultValue = "",required = false) String gid,
                                        @RequestParam(defaultValue = "",required = false) String ordersName){
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        if(!"".equals(uid)){
            ordersQueryWrapper.like("uid",uid);
        }
        if(!"".equals(gid)){
            ordersQueryWrapper.like("gid",gid);
        }
        if(!"".equals(ordersName)){
            ordersQueryWrapper.like("orders_name",ordersName);
        }
        List<Orders> list = ordersService.list(ordersQueryWrapper);
        for(Orders orders:list){
            orders.setGoods(goodsService.getById(orders.getGid()));
        }
        return list;
    }

}

